package com.bw.solr.solr01facet;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.PivotField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.util.NamedList;
import org.junit.Before;
import org.junit.Test;

import com.bw.solr.common.Goods;

/**
 * Facet查询，统计分组信息
 * @author liuxing
 *
 */
public class FacetQuery {
	private HttpSolrClient client = null;

	public static void main(String [] a) throws Exception{
		FacetQuery fq = new FacetQuery();
		fq.init();
		fq.facetpivot();
	}
	
	@Before
	public void init() {
		// 获取solr连接，mycore1是集合名
		client = new HttpSolrClient("http://localhost:28080/solr/mycore");
		System.out.println(client);
	}

	@SuppressWarnings("deprecation")
	@Test
	public void addData() throws Exception {
		DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
		System.out.println("日期"+df.format(new Date(2017-1900, 3, 30)));
		
		List<Goods> gList = new ArrayList<>();
		gList.add(new Goods("1000", "华为手机", 1999d, new Date(2017-1900, 3, 12), "电子"));
		gList.add(new Goods("10001", "华为手机-荣耀", 1999d, new Date(2017-1900, 3, 13), "电子"));
		gList.add(new Goods("10002", "华为手机-mate", 1999d, new Date(2017-1900, 3, 22), "电子"));
		gList.add(new Goods("1001", "童装", 33d, new Date(2017-1900, 4, 5), "服装"));
		gList.add(new Goods("1002", "红蜻蜓", 500d, new Date(2017-1900, 5, 8), "服装"));
		gList.add(new Goods("1003", "TP-Link路由器", 120d, new Date(2017-1900, 6, 20), "电子"));
		gList.add(new Goods("1004", "小米路由器", 130d, new Date(2017-1900, 7, 2), "电子"));
		gList.add(new Goods("1005", "篮球", 150d, new Date(2017-1900, 8, 3), "娱乐"));
		client.addBeans(gList);
		client.commit();
	}

	@Test
	public void facet() throws Exception {
		SolrQuery q = new SolrQuery();
		q.setQuery("*:*");
//		q.setQuery("category_s:电子");
		// 设置Facet属性
		q.setFacet(true);// 开启facet
//		 q.setFacetPrefix("电"); //设置前缀
//		 q.setFacetLimit(3);//限制返回数量（返回结果）
//		 q.setFacetMinCount(2);//控制最小数量，分组后低于这个数量的将不返回
		q.addFacetField("category_s");
		System.out.println(q.toString());
		QueryResponse r = client.query(q);
		
		SolrDocumentList results = r.getResults();
		for (SolrDocument sd : results){
			System.out.println(sd);
		}
		
		List<FacetField> facetFields = r.getFacetFields();
		for (FacetField facet : facetFields) {
			System.out.println(facet.getName());
			System.out.println(facet.getGap());
			System.out.println(facet.getEnd());
			System.out.println("----------------");
			List<Count> counts = facet.getValues();
			for (Count count : counts) {
				System.out.println(count.getName() + ":" + count.getCount());
			}
			System.out.println();
		}
	}

	@Test
	public void facetDate() throws Exception {
		SolrQuery q = new SolrQuery();
		q.setQuery("*:*");
		// 设置Facet属性
//		q.setFacet(true);// 开启facet
		// q.setFacetPrefix("l"); //设置前缀
		// q.setFacetLimit(2);//限制返回数量
		// q.setFacetMinCount(2);//控制最小数量，分组后低于这个数量的将不返回
//		q.addFacetField("date_dt");
		q.set("facet","on");
		q.set("facet.date","date_dt");
		q.set("facet.date.start","2017-05-22T17:33:18.333Z");
		q.set("facet.date.end","2017-09-22T17:33:18.333Z");
		q.set("facet.date.gap","+1MONTH");
		q.set("facet.date.other","all");
		System.out.println(q.toString());
		QueryResponse r = client.query(q);
//		List<FacetField> facetFields = r.getFacetFields();
		List<FacetField> facetFields = r.getFacetDates();
		for (FacetField facet : facetFields) {
			System.out.println(facet.getName());
			System.out.println("----------------");
			List<Count> counts = facet.getValues();
			for (Count count : counts) {
				System.out.println(count.getName() + ":" + count.getCount());
			}
			System.out.println();
		}
	}

	/**
	 * NamedList，一个有序的name/value容器，NamedList不像Map， 他具有以下特点： 
	 * 1、名字可以重复      
	 * 2、NamedList中的element保持这有序状态       
	 * 3、可以下标的形式访问Elements      
	 * 4、name和value都可以为null
	 * 
	 * @throws Exception
	 */
	@Test
	public void facetpivot() throws Exception {
		SolrQuery sQuery = new SolrQuery();
		sQuery.setFacet(true);
		sQuery.set("q", "*:*");
//		sQuery.setFacetLimit(2);//限制返回数量（返回结果）
		sQuery.add("facet.pivot", "category_s,price,id");// 两维度来分组查询
		System.out.println(sQuery.toString());
		QueryResponse response = client.query(sQuery, SolrRequest.METHOD.POST);
		NamedList<List<PivotField>> namedList = response.getFacetPivot();
		List<PivotField> pivotList = null;
		for (int i = 0; i < namedList.size(); i++) { // 此处的多次循环可以用递归
			pivotList = namedList.getVal(i);
			if (pivotList != null) {
				for (PivotField pivot : pivotList) {
					showPivotField(pivot, 1);
				}
			}
		}
	}

	/**
	 * 递归显示
	 * 
	 * @param field
	 * @param level
	 * @throws Exception
	 */
	private void showPivotField(PivotField field, int level) throws Exception {
		for (int i = 0; i < level - 1; i++)
			System.out.print("\t");
		System.out.print("第" + level + "级 : " + field.getValue() + "   " + field.getCount() + "\n");
		List<PivotField> fieldList = field.getPivot();
		if (fieldList != null) {
			for (PivotField f : fieldList) {
				showPivotField(f, level + 1);
			}
		}
	}
	
}
